﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using DSkin.Forms;
using HttpCodeLib;
using Newtonsoft.Json.Linq;

namespace QQLogin
{
    public partial class FrmSingle : Skin_VS_Light
    {
        /// <summary>
        /// 短信平台
        /// </summary>
        private ISmsPlatform smsPlatform;

        public FrmSingle()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 短信平台登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            var userName = txtUser.Text.Trim();
            var password = txtPass.Text.Trim();
            var yumi = rbtnYuMi.Checked;
            if (userName == "" || password == "")
            {
                return;
            }
            ThreadPool.QueueUserWorkItem(s =>
            {
                if (yumi)
                {
                    smsPlatform = new YuMiPlatform { Pid = 3274 };
                    if (!smsPlatform.Login(userName, password, out string msg))
                    {
                        Invoke(new Action(() =>
                        {
                            DSkinMessageBox.Show(msg);
                        }));
                        return;
                    }
                }
                else
                {
                    //极速
                }
                Invoke(new Action(() =>
                {
                    btnLogin.Enabled = false;
                    btnLogout.Enabled = true;
                    txtUser.Enabled = false;
                    txtPass.Enabled = false;
                }));
                Log("打码平台登录成功");
            });
        }

        /// <summary>
        /// QQ登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQqLogin_Click(object sender, EventArgs e)
        {
            var frmQqLogin = new FrmQqLogin();
            if (frmQqLogin.ShowDialog() == DialogResult.OK)
            {
                pbxHead.ImageLocation = $"http://q1.qlogo.cn/g?b=qq&nk={PublicInfo.QQ}&s=100";
                Log($"{PublicInfo.QQ} 登录成功");
                ThreadPool.QueueUserWorkItem(s =>
                {
                    Log($"{PublicInfo.QQ} {Query()}");
                });
            }
        }

        private void Log(string msg)
        {
            msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " >>>> " + msg + "\r\n";
            Invoke((Action)(() =>
            {
                txtLog.AppendText(msg);
                txtLog.ScrollToCaret();
            }));
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            smsPlatform = null;
            txtUser.Enabled = true;
            txtPass.Enabled = true;
            btnLogin.Enabled = true;
            btnLogout.Enabled = false;
            Log("打码平台退出成功");
        }

        private void btnBind_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(PublicInfo.Cookies))
            {
                Log("请先登录QQ");
                return;
            }
            if (smsPlatform == null)
            {
                Log("请先登录打码平台");
                return;
            }
            ThreadPool.QueueUserWorkItem(s =>
            {
                SmsModel model = null;
                var phone = "";
                var msg = "";
                while (true)
                {
                    model = smsPlatform.GetMobileNum();
                    if (!model.Success)
                    {
                        Log(model.Message);
                        return;
                    }
                    phone = model.Data;
                    Log($"{PublicInfo.QQ} 手机号获取成功：{phone}");
                    if (!GetCode(phone, out msg))
                    {
                        Log(msg);
                        if (msg == "手机已经绑定过")
                        {
                            smsPlatform.AddIgnoreList(phone);
                            continue;
                        }
                        return;
                    }
                    break;
                }
                Log($"{PublicInfo.QQ} 验证码发送成功");
                for (int i = 0; i < 20; i++)
                {
                    model = smsPlatform.GetCode(phone);
                    if (!model.Success)
                    {
                        Log($"{PublicInfo.QQ} 正在获取验证码...[{i}]");
                        Thread.Sleep(3000);
                        continue;
                    }
                    break;
                }
                if (!model.Success)
                {
                    smsPlatform.AddIgnoreList(phone);
                    Log(model.Message);
                    return;
                }
                var smsCode = new Regex("【腾讯视频】(.*?) 腾讯视频VIP验证码").Match(model.Data).Groups[1].Value;
                Log($"{PublicInfo.QQ} 验证码获取成功：{smsCode}");
                var flag = Bind(phone, smsCode, out msg);
                Log($"{PublicInfo.QQ} {msg}");
            });
        }

        private readonly static HttpHelpers helper = new HttpHelpers();
        private readonly static XJHTTP xjHttp = new XJHTTP();

        public string Query()
        {
            try
            {
                var item = new HttpItems
                {
                    URL = $"http://pay.video.qq.com/fcgi-bin/payvip?otype=json&getannual=1&uin={PublicInfo.QQ}&t=0&getqquvip=1&g_tk={PublicInfo.Gtk}&_={xjHttp.GetTimeByJs()}&callback=Zepto1532046787343",
                    Cookie = PublicInfo.Cookies,
                    Referer = "http://film.qq.com/weixin/topic/binding.html"
                };
                var html = helper.GetHtml(item).Html.Replace("Zepto1532046787343(", "").Replace(")", "");
                var obj = JObject.Parse(html);
                if (obj["vip"].ToString() == "0")
                {
                    return "您还不是腾讯视频VIP";
                }
                var endTime = obj["endTime"].ToString();
                return $"您的VIP到期时间为：{endTime}";
            }
            catch (Exception ex)
            {
                return $"查询异常：{ex.Message}";
            }
            //{"annualbegintime":1526935069,"annualendtime":1559075862,"annualneedtime":32140800,"annualvip":1,"beginTime":"2018-05-22 04:37:42","canImport":0,"dailyscore":15,"endTime":"2019-05-29 04:37:42","isLoginCheckFail":0,"level":3,"nextgivedate":1532275200,"qquvip":{"beginTime":"2018-05-22 04:37:42","endTime":"2019-05-29 04:37:42","vip":1},"result":{"code":0,"msg":"OK"},"score":2080,"servicetype":"TXSP","uin":49866649,"vip":1}

            //{"annualbegintime":0,"annualendtime":0,"annualneedtime":32140800,"annualvip":0,"beginTime":"","canImport":0,"dailyscore":-5,"endTime":"","isLoginCheckFail":0,"level":0,"nextgivedate":0,"qquvip":{"beginTime":"","endTime":"","vip":0},"result":{"code":0,"msg":"OK"},"score":0,"servicetype":"","uin":675358209,"vip":0}
        }

        public bool GetCode(string phone, out string msg)
        {
            var item = new HttpItems
            {
                URL = $"http://vip.video.qq.com/fcgi-bin/comm_cgi?name=bindphone&otype=json&cmd=16&_t=7&sid={phone}&code=&act=&from=aphone&_=1531920037671&callback=Zepto1531920028005",
                Cookie = PublicInfo.Cookies,
                Referer = "http://film.qq.com/weixin/topic/binding.html",
                UserAgent = "Mozilla/5.0 (Linux; Android 6.0; PRO 6 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043221 Safari/537.36 V1_AND_SQ_7.0.0_676_YYB_D QQ/7.0.0.3135 NetType/WIFI WebP/0.3.0 Pixel/1080"
            };
            var html = helper.GetHtml(item).Html.Replace("Zepto1531920028005(", "").Replace(");", "");
            var obj = JObject.Parse(html);
            var ret = obj["ret"].ToString();
            if (ret != "0")
            {
                msg = "验证码发送失败";
                return false;
            }
            if (obj["bind_user_flag"].ToString() == "1")
            {
                msg = "手机已经绑定过";
                return false;
            }
            item = new HttpItems
            {
                URL = $"http://vip.video.qq.com/fcgi-bin/comm_cgi?name=bindphone&otype=json&cmd=1&_t=1&sid={phone}&code=&act=&from=aphone&_={xjHttp.GetTimeByJs()}&callback=Zepto1531925979241",
                Cookie = PublicInfo.Cookies,
                Referer = "http://film.qq.com/weixin/topic/binding.html",
                UserAgent = "Mozilla/5.0 (Linux; Android 6.0; PRO 6 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043221 Safari/537.36 V1_AND_SQ_7.0.0_676_YYB_D QQ/7.0.0.3135 NetType/WIFI WebP/0.3.0 Pixel/1080"
            };
            html = helper.GetHtml(item).Html.Replace("Zepto1531925979241(", "").Replace(");", "");
            //{"act":0,"allow_bind":0,"result":{"code":0,"msg":"OK"}}
            msg = html;
            return true;
        }

        public bool Bind(string phone, string code, out string msg)
        {
            var item = new HttpItems
            {
                URL = $"http://vip.video.qq.com/fcgi-bin/comm_cgi?name=bindphone&otype=json&cmd=1&_t=0&sid={phone}&code={code}&act=act&from=aphone&_={xjHttp.GetTimeByJs()}&callback=Zepto1531920028007",
                Cookie = PublicInfo.Cookies,
                Referer = "http://film.qq.com/weixin/topic/binding.html",
                UserAgent = "Mozilla/5.0 (Linux; Android 6.0; PRO 6 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043221 Safari/537.36 V1_AND_SQ_7.0.0_676_YYB_D QQ/7.0.0.3135 NetType/WIFI WebP/0.3.0 Pixel/1080"
            };
            var html = helper.GetHtml(item).Html.Replace("Zepto1531920028007(", "").Replace(");", "");
            var obj = JObject.Parse(html);
            if (obj["result"]["code"].ToString() != "0")
            {
                msg = obj["result"]["msg"].ToString();
                return false;
            }
            if (obj["match"].ToString() == "0")
            {
                msg = obj["result"]["msg"].ToString();
                return false;
            }
            msg = "绑定成功";
            return true;
        }
    }
}
